from django.conf import settings
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse, HttpResponsePermanentRedirect
from django.views import View
from django.utils import timezone
from django.db.models import Q, F
from iClouds.mktoken import get_tokens_for_user
from iClouds.Authentication import MyJWTAuthentication
from mysqldb import redis as REDIS
from mysqldb.models import AllinpayUserList, AllinpayAuthGroup


USER = MyJWTAuthentication()


# Create your views here.
class Login(View):
    def get(self, request):
        return render(request, "upstage/login.html")

    def post(self, request):
        return render(request, "upstage/login.html")


class Index(View):
    def get(self, request):
        token = request.COOKIES.get("token")
        # 解密token 获取uid
        validated_token = USER.get_validated_token(token.encode("utf-8"))
        user = USER.get_user(validated_token)
        try:
            userinfo = user
            role = AllinpayAuthGroup.objects.get(id=userinfo.group)
        except BaseException as err:
            raise ValueError({"index": "No User"})
        else:
            return render(
                request,
                "upstage/bs5.html",
                {
                    "Authorization": token,
                    "userinfo": {
                        "id": userinfo.id,
                        "nicename": userinfo.basename,
                        "basename": userinfo.name,
                        "phone": userinfo.phone[:3] + "****" + userinfo.phone[-3:],
                        "email": None
                        if not userinfo.email
                        else userinfo.email[:2] + "***@" + userinfo.email.split("@")[1],
                        "face": userinfo.avatar,
                        "creatime": userinfo.creattime,
                        "lastime": userinfo.last_login,
                        "group": role.name,
                    },
                },
            )

    def post(self, request):
        return HttpResponse("No Pages")
